package com.richfit.barcodesystem_cczt.utils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.richfit.barcodesystem_cczt.R;
import com.richfit.barcodesystem_cczt.utils.constant.Global;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


public class CommonUtils {
    // 建立一个MIME类型与文件后缀名的匹配表
    static final String[][] MIME_MapTable = {
            // {后缀名， MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"}, {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"}, {".bmp", "image/bmp"},
            {".c", "text/plain"}, {".class", "application/octet-stream"},
            {".conf", "text/plain"}, {".cpp", "text/plain"},
            {".doc", "application/msword"}, {".dot", "application/msword"},

            {".xla", "application/vnd.ms-excel"},
            {".xlc", " application/vnd.ms-excel"},
            {".xll", "application/vnd.ms-excel"},
            {".xlm", " application/vnd.ms-excel"},
            {".xls", "application/vnd.ms-excel"},
            {".xlt", " application/vnd.ms-excel"},
            {".xlw", "application/vnd.ms-excel"},

            {".exe", "application/octet-stream"}, {".gif", "image/gif"},
            {".gtar", "application/x-gtar"}, {".gz", "application/x-gzip"},
            {".h", "text/plain"}, {".htm", "text/html"},
            {".html", "text/html"}, {".jar", "application/java-archive"},
            {".java", "text/plain"}, {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"}, {".js", "application/x-javascript"},
            {".log", "text/plain"}, {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"}, {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"}, {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"}, {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"}, {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"}, {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"}, {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"}, {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"}, {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".prop", "text/plain"},
            {".rar", "application/x-rar-compressed"},
            {".rc", "text/plain"}, {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"}, {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"}, {".txt", "text/plain"},

            {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"},
            {".z", "application/x-compress"}, {".zip", "application/zip"},
            {"", "*/*"}};

    /**
     * 判断URL地址
     *
     * @param url
     * @return
     */
    public static String getUrl(String url) {
        String Url = "";
        if (url == null || "".equals(url.trim())) {
            return url;
        }
//        if (url.indexOf("http") != 0) {
//            Url = Urls.http_img + url;
//        } else {
//            Url = url;
//        }
        return Url;
    }

    public static boolean isSdCardExist() {
        boolean isExist = false;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            isExist = true;
        }
        return isExist;
    }

    /**
     * 检测网络链接
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 计算指定日期时间之间的时间差
     *
     * @param beginStr 开始日期字符串
     * @param f        时间差的形式0-秒,1-分种,2-小时,3--天 日期时间字符串格式:yyyyMMddHHmmss
     */
    static long getInterval(String beginStr, int f) throws Exception {
        long hours = 0;
        try {

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date beginDate = df.parse(beginStr);
            // Date endDate = df.parse(endStr);
            Date endDate = new Date();
            long millisecond = endDate.getTime() - beginDate.getTime(); // 日期相减得到日期差X(单位:毫秒)
            /**
             * 1秒 = 1000毫秒 millisecond/1000 --> 秒 millisecond/1000*60 - > 分钟
             * millisecond/(1000*60*60) -- > 小时 millisecond/(1000*60*60*24) -->
             * 天
             * */
            switch (f) {
                case 0: // second
                    return Math.abs(millisecond / 1000);
                case 1: // minute
                    return Math.abs(millisecond / (1000 * 60));
                case 2: // hour
                    return Math.abs(millisecond / (1000 * 60 * 60));
                case 3: // day
                    return Math
                            .abs((long) (millisecond / (1000 * 60 * 60 * 24) + 0.5));

            }
        } catch (Exception e) {
            throw e;
        }
        return hours;
    }

    public static String[] getChByArry(String[] a) {
        if (null != a && a.length > 0) {
            String[] b = new String[a.length];
            int len = a.length;
            int i = 0;
            for (; i < len; i++) {
                b[i] = getCh(a[i]);
            }
            return b;
        }
        return null;
    }

    /**
     * 使用正则表达式提取中文
     *
     * @param str
     * @return
     */
    public static String getCh(String str) {
        if (str == null || "".equals(str.trim())) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        char[] aa = str.toCharArray();
        for (int i = 0; i < aa.length; i++) {
            char c = aa[i];
            if (Pattern.matches("[\u4e00-\u9fa5]+", String.valueOf(c))
                    || ",".equals(String.valueOf(c))) {
                sb.append(c);
            }

        }
        return sb.toString();
    }

    //从html中提取纯文本
    public static String StripHT(String strHtml) {
        String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
        txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
        return txtcontent;
    }

    /**
     * 替换指定字符串
     *
     * @param str
     * @param oldStr
     * @param newStr
     * @return
     */
    public static String replaceAll(String str, String oldStr, String newStr) {
        int oldStrLength = oldStr.length();
        StringBuffer dest = new StringBuffer();
        int index = str.indexOf(oldStr);
        if (index == -1) {
            dest.append(str);
        } else {
            dest.append(str.substring(0, index));
        }
        while (index != -1) {
            dest.append(newStr);
            int beforeIndex = index;
            index = str.indexOf(oldStr, index + oldStrLength);
            if (index == -1) {
                dest.append(str.substring(beforeIndex + oldStrLength));
            } else {
                dest.append(str.substring(beforeIndex + oldStrLength, index));
            }
        }
        return dest.toString();
    }

    public static String formatData(String beginStr) {
        StringBuffer sb = new StringBuffer();
        try {
            long m = getInterval(beginStr, 1);
            if (m == 0) {
                sb.append("刚刚");
            } else if (m < 60) {
                sb.append(m);
                sb.append("分钟前");
            } else if (m < 24 * 60 && m >= 60) {
                sb.append(getInterval(beginStr, 2));
                sb.append("小时前");
            } else if (m >= 24 * 60 && m < 24 * 60 * 3) {
                sb.append(getInterval(beginStr, 3));
                sb.append("天前");
            } else {
                if (beginStr != null && !"".equals(beginStr)) {
                    String[] a = beginStr.split(" ");
                    sb.append(a[0]);
                } else {
                    sb.append("");
                }

            }
        } catch (Exception e) {
            sb.append(beginStr);
        }

        return sb.toString();
    }

    /**
     * 当前时间
     *
     * @param format 时间格式
     * @return
     */
    public static String getNow(String format) {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat f = new SimpleDateFormat(format);
        return f.format(c.getTime());

    }

    /**
     * 创建文件
     *
     * @param datas
     * @param fileName
     * @return
     */
    public static File createFile(byte[] datas, String fileName) {
        FileOutputStream fileOutputStream = null;
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory(), fileName);
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(datas);
            fileOutputStream.flush();
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {

            e.printStackTrace();
        }

        return file;

    }

    /**
     * @param value
     * @return
     */
    public static String splitLength(String value) {
        String s = value.subSequence(0, 2) + ":";
        s += value.substring(2, 4);
        return s;
    }

    public static void showInfo(Context context, String info) {
        Toast.makeText(context, info, Toast.LENGTH_SHORT).show();
    }

    public static String getStr(String str) {
        if (str == null) {
            return "";
        } else if ("null".equals(str)) {
            return "";

        } else {
            return str;
        }
    }

    /**
     * @param context
     * @param str     需要验证字符
     * @param errinfo 错误提示信息
     */
    public static void validateEmpty(Context context, String str, String errinfo) {
        if (str == null || "".equals(str)) {
            Toast.makeText(context, errinfo, Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * @param context
     * @param str     需要验证字符
     * @param errinfo 错误提示信息
     * @param rexstr  验证正则
     */
    public static void validateRegx(Context context, String str,
                                    String errinfo, String rexstr) {
        Pattern pattern = Pattern.compile(rexstr);
        Matcher m = pattern.matcher(str);
        if (!m.matches()) {
            Toast.makeText(context, errinfo, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * @param context
     * @param handler
     * @param title
     * @param content
     */
    public static void showError(final Context context, Handler handler,
                                 final String title, final String content) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder build = new AlertDialog.Builder(context);
                build.setTitle(title)
                        .setMessage(content)
                        .setIcon(R.mipmap.alert2)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.dismiss();
                                    }
                                });

                build.show();

            }
        });

    }

    /**
     * @param context
     * @param handler
     * @param progressDialog
     * @param title
     * @param content
     */
    public static void showError(final Context context, Handler handler,
                                 final ProgressDialog progressDialog, final String title,
                                 final String content) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder build = new AlertDialog.Builder(context);
                build.setTitle(title)
                        .setMessage(content)
                        .setIcon(R.mipmap.alert2)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.dismiss();
                                        if (progressDialog != null) {
                                            progressDialog.cancel();
                                        }
                                    }
                                });

                build.show();

            }
        });

    }

    /**
     * 返回当天日期 yyyy-MM-dd
     *
     * @param format
     * @return
     */
    public static String getDay(String format) {
        // yyyy-MM-dd
        DateFormat df = new SimpleDateFormat(format);
        // //System.out.println("df.format(new Date())====>" + df.format(new
        // Date()));
        return df.format(new Date());

    }

    /**
     * 返回本周第一天 （周日开始---周六结束） yyyy-MM-dd
     *
     * @param format
     * @return
     */
    public static String getStartDayOfWeek(String format) {
        DateFormat df = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        Calendar cpcalendar = (Calendar) calendar.clone();
        cpcalendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return df.format(new Date(cpcalendar.getTimeInMillis()));

    }

    /**
     * 返回本周最后一天 （周日开始---周六结束） yyyy-MM-dd
     *
     * @param format
     * @return
     */
    public static String getEndDayOfWeek(String format) {
        DateFormat df = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        Calendar cpcalendar = (Calendar) calendar.clone();
        cpcalendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        return df.format(new Date(cpcalendar.getTimeInMillis()));

    }

    /**
     * 返回本月第一天 yyyy-MM-dd
     *
     * @param format
     * @return
     */
    public static String getStartDayOfMonth(String format) {
        DateFormat df = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        Calendar cpcalendar = (Calendar) calendar.clone();
        cpcalendar.set(Calendar.DAY_OF_MONTH, 1);
        return df.format(new Date(cpcalendar.getTimeInMillis()));
    }

    /**
     * 返回本月最后一天 yyyy-MM-dd
     *
     * @param format
     * @return
     */
    public static String getEndDayOfMonth(String format) {
        DateFormat df = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        Calendar cpcalendar = (Calendar) calendar.clone();
        cpcalendar.set(Calendar.DAY_OF_MONTH, 1);
        cpcalendar.add(Calendar.MONTH, 1);
        cpcalendar.add(Calendar.DATE, -1);
        return df.format(new Date(cpcalendar.getTimeInMillis()));
    }

    public static Date stringToDate(String str, String fat) {
        DateFormat format = new SimpleDateFormat(fat);
        Date date = null;
        try {
            // Fri Feb 24 00:00:00 CST 2012
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 2012-02-24
        date = java.sql.Date.valueOf(str);

        return date;
    }

    public static int parseInt(String str) {
        int i = 0;
        if (str == null || "".equals(str)) {

        } else {
            i = Integer.parseInt(str);
        }
        return i;
    }

    /**
     * str转化为float
     *
     * @param str
     * @return
     */
    public static float parseFloat(String str) {
        float i = 0.0f;
        if (str == null || "".equals(str)) {

        } else {
            i = Float.parseFloat(str);

        }
        return i;
    }

    /**
     * 保留两位小数
     *
     * @return
     */
    public static String formatFloat(float i) {
        NumberFormat formater = java.text.DecimalFormat.getInstance();
        formater.setMaximumFractionDigits(2);
        formater.setMinimumFractionDigits(2);
        formater.setGroupingUsed(false); // 去掉逗号 123,2.33 ==> 1232.33
        return formater.format(i);
    }

    /**
     * 将转义字符 换成正常字符
     *
     * @param s
     * @return
     */
    public static String htmlEncode(String s) {
        if ((s != null) && (s != "") && s.contains("&")) {
            String s1 = s.replace("&amp;", "&");// &amp; 转义&
            String s2 = s1.replace("&lt;", "<");// &lt; 转义 <
            String s3 = s2.replace("&gt;", ">");// &gt; 转义 >
            String s4 = s3.replace("&quot;", "\"");// &quot; 转义 "
            return s4;
        } else {
            return s;
        }

    }

    /**
     * 把View存为Bitmap对象
     *
     * @param v
     * @return
     */
    public static Bitmap getViewBitmap(View v) {
        Bitmap bitmap = null;
        if (v != null) {
            v.clearFocus();
            v.setPressed(false);
            boolean willNotCache = v.willNotCacheDrawing();
            v.setWillNotCacheDrawing(false);
            // Reset the drawing cache background color to fully transparent
            // for the duration of this operation
            int color = v.getDrawingCacheBackgroundColor();
            v.setDrawingCacheBackgroundColor(0);
            if (color != 0) {
                v.destroyDrawingCache();
            }
            v.buildDrawingCache();
            Bitmap cacheBitmap = v.getDrawingCache();
            if (cacheBitmap == null) {
                Log.e("getViewBitmap", "failed getViewBitmap(" + v + ")",
                        new RuntimeException());

                return null;
            }
            bitmap = Bitmap.createBitmap(cacheBitmap);
            // Restore the view
            v.destroyDrawingCache();
            v.setWillNotCacheDrawing(willNotCache);
            v.setDrawingCacheBackgroundColor(color);
            if (cacheBitmap != null) {
                cacheBitmap.recycle();
                cacheBitmap = null;
            }

            // v=null;

        }

        return bitmap;
    }

    /**
     * 设置文件类型图标
     *
     * @param fileName
     * @return
     */
    public static int showFilePic(String fileName) {
        int picId;
        if (fileName.toLowerCase().indexOf(".txt") > 0) {
            picId = R.mipmap.txt;
        } else if (fileName.toLowerCase().indexOf(".doc") > 0) {
            picId = R.mipmap.doc;

        } else if (fileName.toLowerCase().indexOf(".xls") > 0) {
            picId = R.mipmap.xls;
        } else if (fileName.toLowerCase().indexOf(".pdf") > 0) {
            picId = R.mipmap.pdf;

        } else if (fileName.toLowerCase().indexOf(".gif") > 0) {
            picId = R.mipmap.gif;

        } else if (fileName.toLowerCase().indexOf(".swf") > 0) {
            picId = R.mipmap.swf;

        } else if (fileName.toLowerCase().indexOf(".jpeg") > 0) {
            picId = R.mipmap.jpeg;
        } else if (fileName.toLowerCase().indexOf(".jpg") > 0) {
            picId = R.mipmap.jpeg;
        } else if (fileName.toLowerCase().indexOf(".bmp") > 0) {
            picId = R.mipmap.bmp;

        } else if (fileName.toLowerCase().indexOf(".png") > 0) {
            picId = R.mipmap.png;
        } else if (fileName.toLowerCase().indexOf(".xml") > 0) {
            picId = R.mipmap.xml;
        } else if (fileName.toLowerCase().indexOf(".mdb") > 0) {
            picId = R.mipmap.mdb;
        } else if (fileName.toLowerCase().indexOf(".htm") > 0) {
            picId = R.mipmap.html;
        } else if (fileName.toLowerCase().indexOf(".mp3") > 0) {
            picId = R.mipmap.mp3;
        } else if (fileName.toLowerCase().indexOf(".wma") > 0) {
            picId = R.mipmap.mp3;
        } else if (fileName.toLowerCase().indexOf(".rm") > 0) {
            picId = R.mipmap.mp3;
        } else {
            picId = R.mipmap.file;
        }
        return picId;

    }

    public static String setFileSize(int fileSize) {
        String result = "0b";
        if (fileSize < 1024) {
            result = fileSize + "b";
        } else if (fileSize > 1024 && fileSize < 1024 * 1024) {
            result = fileSize / 1024 + "kb";
        } else if (fileSize > 1024 * 1024 && fileSize < 1024 * 1024 * 1024) {
            result = fileSize / (1024 * 1024) + "M";
        }

        return result;
    }

    /**
     * 打开文件
     *
     * @param file
     */
    public static void openFile(File file, Context context) {
        Intent intent = new Intent();

        String fName = file.getName();
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            // 文件没有后缀名
            Toast.makeText(context, "无法识别的文件类型!", Toast.LENGTH_LONG).show();
            return;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex).toLowerCase();
        // if (end.indexOf("txt") != -1 || end.indexOf("htm") != -1) {
        // intent.setClass(context, ShowTxtAndWeb.class);
        // intent.putExtra("url", file.getPath());
        // context.startActivity(intent);
        // } else {

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
        // 获取文件file的MIME类型
        String type = getMIMEType(file);
        // 设置intent的data和Type属性。
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "该文件类型无法打开!", Toast.LENGTH_LONG).show();
        }

        // }

    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     *
     * @param file
     */
    public static String getMIMEType(File file) {
        String type = "*/*";
        String fName = file.getName();
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex).toLowerCase();
        if (end == "") {
            return type;
        }
        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0])) {
                type = MIME_MapTable[i][1];
            }
        }
        return type;
    }

    /**
     * 通过 服务器地址 拆分出 端口号
     */
    public static String getPort(String webAddress) {
        // http://172.16.0.54:8080/oaservice.json?
        String port = "";
        if (webAddress.contains("://")) {
            String[] strs = webAddress.split("//");
            if (strs[1].contains("/")) {
                String[] strss = strs[1].split("/");
                if (strss[0].contains(":")) {
                    String[] strsss = strss[0].split(":");
                    port = strsss[1];
                }
            }
        }
        return port;
    }

    /**
     * 通过 服务器地址 拆分出 ip
     */
    public static String getIp(String webAddress) {
        ////System.out.println(webAddress);
        // http://172.16.0.54:8080/oaservice.json?
        //http://172.16.42.33:8080/WebService.asmx/WebServiesTable?op=WebServiesTable
        String ip = "";
        if (webAddress.contains("//")) {
            String[] strs = webAddress.split("://");
            if (strs[1].contains("/")) {
                String[] strss = strs[1].split("/");
                if (strss[0].contains(":")) {
                    String[] strsss = strss[0].split(":");
                    ip = strsss[0];
                }
            }
        }
        return ip;
    }

    /**
     * 通过ip 和端口号 获得完整的 服务器地址
     */
    public static String spliceWebAddress(String ip, String port) {
        StringBuffer webAdd = new StringBuffer();
        // if(!ip.contains("http://")){
        // ip = "http://"+ip;
        // }http://172.16.0.54:8080/oaservice.json?
        webAdd.append("http://" + ip + ":" + port + "/WebService.asmx");
        return webAdd.toString();
    }

    /**
     * 通过ip 和端口号 获得完整的 服务器地址  用于更新
     */

    /**
     * 通过ip 和端口号 获得完整的 服务器地址
     */
    public static String spliceWebAddress2(String ip, String port) {
        StringBuffer webAdd = new StringBuffer();
        // if(!ip.contains("http://")){
        // ip = "http://"+ip;
        // }http://172.16.0.54:8080/oaservice.json?
        webAdd.append("http://" + ip + ":" + port + "/Handler.ashx?type=4");
        return webAdd.toString();
    }


    public static String formatTitleStr(String str, int textViewLine,
                                        int timeSize) {
        if (str != null && str.length() > textViewLine) {
            if (str.length() > (textViewLine * 2 - timeSize)) {
                str = str.substring(0, (textViewLine * 2 - timeSize - 3))
                        + "...";
            }
        }
        return str;
    }

    // 替换、过滤特殊字符
    public static String StringFilter(String str) throws PatternSyntaxException {
        str = str.replaceAll("【", "[").replaceAll("】", "]")
                .replaceAll("！", "!");// 替换中文标号
        String regEx = "[『』]"; // 清除掉特殊字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static ArrayList<File> ls_Directory(String directory) {
        Runtime shell = Runtime.getRuntime();
        ArrayList<File> allFile = new ArrayList<File>();
        // if (directory.equals("/"))
        // directory = "";
        String[] cmds = {"ls", "-a", directory};
        BufferedReader br = null;
        try {
            Process mProcess = shell.exec(cmds);
            br = new BufferedReader(new InputStreamReader(
                    mProcess.getInputStream()));
            String line = null;
            //System.out.println("打印所有正在运行的进程信息");
            while ((line = br.readLine()) != null) {
                //System.out.println(br.readLine());
                if (line.length() > 0) {
                    File file = new File(directory + line);
                    //System.out.println(file.getPath());
                    if (file.exists()) {
                        allFile.add(file);
                    }
                }

            }
        } catch (IOException e) {
            // e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return allFile;
    }

    /**
     * 判断对象是否为空或null
     */
    public static Boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }

        if (obj instanceof CharSequence) {
            return ((CharSequence) obj).length() == 0;
        }
        if (obj.getClass().isArray()) {
            return Array.getLength(obj) == 0;
        }
        if (obj instanceof Collection) {
            return ((Collection) obj).isEmpty();
        }
        if (obj instanceof Map) {
            return ((Map) obj).isEmpty();
        }

        // else
        return false;
    }

    public static int createModuleIcon(String moduleCode) {

        if (TextUtils.isEmpty(moduleCode)) {
            return 0;
        }
        switch (moduleCode) {
            case Global.WZYS:
                return R.mipmap.icon_module1;
            case Global.WZRK:
                return R.mipmap.icon_module2;
            case Global.WZCK:
                return R.mipmap.icon_module3;
            case Global.WZTK:
                return R.mipmap.icon_module4;
            case Global.WZYK:
                return R.mipmap.icon_module5;
            case Global.WZTH:
                return R.mipmap.icon_module6;
            case Global.WZPD:
                return R.mipmap.icon_module7;
            case Global.CWTZ:
                return R.mipmap.icon_module8;
            case Global.XXCX:
                return R.mipmap.icon_module11;
            case Global.DGRK:
                return R.mipmap.icon_module14;
            case Global.DGCK:
                return R.mipmap.icon_module12;
            case Global.SETTING:
                return R.mipmap.icon_module13;
            case Global.DGYK:
                return R.mipmap.icon_module14;
            case Global.L_LOADDATA:
                return R.mipmap.icon_module15;
            case Global.L_UPLOADDATA:
                return R.mipmap.icon_module16;
            case Global.SXCL:
                return R.mipmap.icon_module14;
            case Global.VSCX:
                return R.mipmap.icon_module17;
            case Global.KFXJ:
                return R.mipmap.icon_module18;
            //上架单据查询
            case Global.REF_CX:
                return R.mipmap.icon_module17;
            case Global.WZQY:
                return R.mipmap.icon_module14;
            case Global.ZDLGL:
                return R.mipmap.icon_module10;
        }
        return 0;
    }

}
